<?php
/**
 * Powered By ThinkPHP 5.0.12
 * Created by PhpStorm.
 * Date: 2018/12/25
 * Author: Zhangzhenbei <zhenbeigg@163.com>
 */
namespace app\api\controller;
use think\Db;
class Order extends Common
{
    /**
    * 获取订单列表
    * @return bool
    * @return int $user_id 用户id
    */
    public function get_order_list()
    {
        $user_id = input('param.user_id');
        if(!$user_id){
            json_msg(1,'请求错误');
        }
        $orderAll = $this->getOrderData('',$user_id);
        $order1 = $this->getOrderData(0,$user_id);
        $order2 = $this->getOrderData(1,$user_id);
        $order3 = $this->getOrderData(2,$user_id);
        $order4 = $this->getOrderData(5,$user_id);
        $data['orderAll'] = $orderAll;
        $data['order1'] = $order1;
        $data['order2'] = $order2;
        $data['order3'] = $order3;
        $data['order4'] = $order4;
        json_msg_data(0,'ok',$data);
    }
    /**
     * 获取订单信息
     * @return bool
     */
    public function getOrderData($status,$user_id)
    {
        $where = ['user_id'=>$user_id];
        isset($status) ? $where['status'] = $status : '' ;
        $order = Db::name('goods_order')->where($where)->order('add_time desc')->field('id,sum,order_no,status,cost')->select();
        foreach ($order as $k=>$v)
        {
            $order[$k]['goods'] = edit_img_url(Db::name('goods_order_detail')->where('order_id',$v['id'])->field('goods_id,goods_sell_price,goods_count,goods_title,goods_img_url')->select(),'goods_img_url',1);
        }
        return $order;
    }
    /**
    * 获取订单详情
    * @return bool
    * @return int $orderId 订单id
    */
    public function get_order_id()
    {
        $orderId = input('param.orderId');
        if(!$orderId){
            json_msg(1,'请求错误');
        }
        $order = Db::name('goods_order')->where('id',$orderId)->find();
        $order['goods'] = edit_img_url(Db::name('goods_order_detail')->where('order_id',$order['id'])->field('goods_id,goods_sell_price,goods_count,goods_title,goods_img_url')->select(),'goods_img_url',1);
        if ($order) {
            json_msg_data(0,'ok',$order);
        }else{
            json_msg(1,'订单不存在');
        }

    }
    /**
    * 订单付款前展示
    * @return bool
    * @return int $cartIds 购物车id字符串
    * @return int $goodsId 商品id
    * @return int $goodsCount 商品数量
    * @return int $userId 用户id
    */
    public function get_order_show()
    {
        $cartIds = input('param.cartIds');
        $goodsId = input('param.goodsId');
        $goodsCount = input('param.goodsCount');
        $userId = input('param.userId');
        if(!$userId){
            json_msg(1,'请求错误');
        }
        if ($cartIds) {
            $cartIdArr = array_filter(explode(',',$cartIds));
            $data = [];
            $sum = '';
            foreach ($cartIdArr as $k=>$v)
            {
                $cart = edit_img_url(Db::name('cart')->where('id',$v)->field('goods_id,goods_sell_price,goods_count,goods_img_url,goods_title')->find(),'goods_img_url',2);
                $data['goods'][] = $cart;
                $sum += $cart['goods_sell_price'] * $cart['goods_count'];
                $data['sum'] = $sum;
            }
        }elseif($goodsId){
            if($goodsCount<=0){
                json_msg(1,'商品数量不能小于1');
            }
            $goods_info = edit_img_url(Db::name('goods')->where('id',$goodsId)->field('id goods_id,sell_price goods_sell_price,img_url goods_img_url,title goods_title')->find(),'goods_img_url',2);
            $goods_info['goods_count'] = $goodsCount;
            $data['goods'][] = $goods_info;
            $data['sum'] = $goods_info['goods_sell_price'] * $goodsCount;
        }else{
            json_msg(1,'请求错误');
        }
        $address = Db::name('user_address')->where(['user_id'=>$userId,'is_default'=>1])->find();
        if ($address)
        {
            $cost = get_express_cost($address['province_code']);
            $data['cost'] = $cost;
            $arr['province'] = province($address['province_code']);
            $arr['city'] = city($address['city_code']);
            $arr['area'] = area($address['area_code']);
            $arr['info'] = $address['info'];
            $arr['name'] = $address['name'];
            $arr['mobile'] = $address['mobile'];
            $arr['id'] = $address['id'];
            $data['address'] = $arr;

        }else{
            $data['address'] = 0;
            $data['addressmsg'] = '该用户没有设置收货地址';
        }
        $coupon = get_user_coupon($userId,0,$sum);
        $data['coupon'] = $coupon;
        json_msg_data(0,'ok',$data);
    }
    
    /** 
    * 添加订单
    * @return bool
    * @return int $cartIds 购物车id字符串
    * @return int $goodsId 商品id
    * @return int $goodsCount 商品数量
    * @return int $addressId 地址id
    * @return int $couponId 优惠券id
    * @return int $userId 用户id
    */
    public function add_order()
    {
        $userId = input('param.userId');
        $addressId = input('param.addressId');
        $cartIds = input('param.cartIds');
        $goodsId = input('param.goodsId');
        $goodsCount = input('param.goodsCount');
        $couponId = input('param.couponId');
        if(!$userId || !$addressId){
            json_msg(1,'请求错误');
        }
        $addressData  = Db::name('user_address')->find($addressId);
        $address = province($addressData['province_code']).city($addressData['city_code']).area($addressData['area_code']).$addressData['info'];
        $cost = get_express_cost($addressData['province_code']);
        $name = $addressData['name'];
        $mobile = $addressData['mobile'];

        if($cartIds){
            $cartId = array_filter(explode(',',$cartIds));
            $sum = '';
            foreach ($cartId as $k=>$v)
            {
                $cart = Db::name('cart')->where('id',$v)->field('goods_sell_price,goods_count')->find();
                $sum += $cart['goods_sell_price'] * $cart['goods_count'];
            }
            if ($couponId) {
                $coupon = Db::name('user_coupon')->find($couponId);
                if ($sum<$coupon['astrict']) {
                    json_msg(1,'优惠券不可用');
                }
                Db::name('user_coupon')->delete($couponId);
                $couponMoney = $coupon['money'];
            }
           
            $orderNo='GM'.date('ymdHis',time()).mt_rand(1000,9999);
            $order = [
                'order_no'=>$orderNo,
                'sum' => $sum,
                'cost' => $cost,
                'name'=>$name,
                'mobile'=>$mobile,
                'address'=>$address,
                'user_id'=>$userId,
                'coupon_money'=>$couponMoney,
                'pay_money'=>$sum+$cost-$couponMoney
            ];
            if (Db::name('goods_order')->insert($order))
            {
                $orderId = Db::name('goods_order')->getLastInsID();
                $openId = get_user_info_data($userId,'wx_openid');
                foreach ($cartId as $k=>$v)
                {
                    $cart = Db::name('cart')->where('id',$v)->find();
                    $data[] = [
                        'order_id' => $orderId,
                        'goods_title'=>$cart['goods_title'],
                        'goods_id'=>$cart['goods_id'],
                        'goods_img_url'=>$cart['goods_img_url'],
                        'goods_sell_price'=>$cart['goods_sell_price'],
                        'goods_count'=>$cart['goods_count'],
                        'user_id' => $userId,
                        'wx_openid'=>$openId,
                        'order_no' => $orderNo
                    ];
                }
                Db::name('cart')->delete($cartId);
                $result = Db::name('goods_order_detail')->insertAll($data);
                json_msg_data(0,'订单已提交',['orderNo'=>$orderNo]);
            } else {
                json_msg(1,'订单提交失败,请稍候再试');
            }

        }elseif($goodsId){
            if($goodsCount<=0){
                json_msg(1,'商品数量不能小于1');
            }
            $goods_info = Db::name('goods')->where('id',$goodsId)->find();
            $sum = $goods_info['sell_price'] * $goodsCount;
            if ($couponId)
            {
                $coupon = Db::name('user_coupon')->find($couponId);
                if ($sum<$coupon['astrict']) {
                    json_msg(1,'优惠券不可用');
                }
                Db::name('user_coupon')->delete($couponId);
                $couponMoney = $coupon['money'];
            }
            $orderNo='GM'.date('ymdHis',time()).mt_rand(1000,9999);
            $order = [
                'order_no'=>$orderNo,
                'sum' => $sum,
                'cost' => $cost,
                'name'=>$name,
                'mobile'=>$mobile,
                'address'=>$address,
                'user_id'=>$userId,
                'coupon_money'=>$couponMoney,
                'pay_money'=>$sum+$cost-$couponMoney
            ];
            if (Db::name('goods_order')->insert($order))
            {
                $orderId = Db::name('goods_order')->getLastInsID();
                $openId = get_user_info_data($userId,'wx_openid');
                $data = [
                    'order_id' => $orderId,
                    'goods_title'=>$goods_info['title'],
                    'goods_id'=>$goods_info['id'],
                    'goods_img_url'=>$goods_info['img_url'],
                    'goods_sell_price'=>$goods_info['sell_price'],
                    'goods_count'=>$goodsCount,
                    'user_id' => $userId,
                    'wx_openid'=>$openId,
                    'order_no' => $orderNo
                ];
                $result = Db::name('goods_order_detail')->insert($data);
                json_msg_data(0,'订单已提交',['orderNo'=>$orderNo]);
            } else {
                json_msg(1,'订单提交失败,请稍候再试');
            }

        }else{
            json_msg(1,'请求错误');
        }

    }
    /** 
    * 订单确认收货
    * @return bool
    * @return int $orderId 订单id
    */
    public function order_confirm()
    {
        $orderId = input('param.orderId');
        if(!$orderId){
            json_msg(1,'请求错误');
        }
        $result = Db::name('goods_order')->where('id',$orderId)->update(['status'=>5,'confirm_time'=>date('Y-m-d H:i:s')]);
        if ($result || $result>0)
        {
            json_msg(0,'已经确认收货');
        } else {
            json_msg(1,'操作失败');
        }
    }
    /** 
    * 删除订单
    * @return bool
    * @return int $orderId 订单id
    */
    public function order_delete()
    {
        $orderId = input('param.orderId');
        if(!$orderId){
            json_msg(1,'请求错误');
        }
        $result = Db::name('goods_order')->where('id',$orderId)->delete();
        $row = Db::name('goods_order_detail')->where('order_id',$orderId)->delete();
        if ($result || $row)
        {
            json_msg(0,'已删除');
        } else {
            json_msg(1,'删除失败');
        }
    }
}